import { defineStore } from 'pinia';

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [],
  }),
  getters: {
    // 计算购物车商品总数
    totalItems: (state) => state.items.reduce((total, item) => total + item.quantity, 0),
    // 计算购物车总金额
    totalPrice: (state) => state.items.reduce((total, item) => 
      total + (item.price * item.quantity), 0),
  },
  actions: {
    // 添加商品到购物车
    addToCart(book, quantity = 1) {
      const existingItem = this.items.find(item => item.id === book.id);
      if (existingItem) {
        existingItem.quantity += quantity;
      } else {
        this.items.push({ ...book, quantity });
      }
    },
    // 更新购物车商品数量
    updateQuantity(id, quantity) {
      const item = this.items.find(item => item.id === id);
      if (item) {
        item.quantity = quantity;
      }
    },
    // 从购物车移除商品
    removeFromCart(id) {
      this.items = this.items.filter(item => item.id !== id);
    },
    // 清空购物车
    clearCart() {
      this.items = [];
    },
  },
});